<template>
  <div>
    <div class="cards">
      <Card style="width: 320px" class="card-item" v-for="item in cycleArr" :key="item.id">
        <div style="text-align: center">
          <span>{{ item.status }}</span>
          <img src="../assets/cy.jpg" />
          <h3>{{ item.location }}</h3>
          <div class="btns">
            <Button type="primary" @click="getUse(item)">用车</Button>
            <Button type="primary" @click="returnIt(item)">还车</Button>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>
<script>
import { getBikeInfo, amendBikeInfo, addOrdersInfo } from '../api/index'
export default {
  data() {
    return {
      cycleArr: []
    }
  },
  methods: {
    getCyclesInfo() {
      getBikeInfo().then((res) => {
        console.log(res)
        this.cycleArr = res
      })
    },
    getUse(item) {
      if (item.status !== 'available') {
        return this.$Message.error('车辆已被使用或故障，请更换车辆')
      }
      amendBikeInfo(item.id, {
        status: 'inUsing'
      }).then(() => {
        this.getCyclesInfo()
        this.$Message.success('开锁成功')
      })
    },
    async returnIt(item) {
      if (item.status !== 'inUsing') {
        return this.$Message.error('车辆未使用')
      }
      await amendBikeInfo(item.id, {
        status: 'available'
      }).then(() => {
        this.getCyclesInfo()
        this.$Message.success('关锁成功')
      })
      // 生成订单
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || {})
      addOrdersInfo({
        user_id: userInfo.id,
        bike_id: item.id,
        start_time: '2021-01-01 10:00:00',
        end_time: new Date(),
        status: 'completed'
      })
    }
  },
  created() {
    this.getCyclesInfo()
  }
}
</script>

<style scoped lang="scss">
img {
  width: 200px;
}
.cards {
  width: 100%;
  display: grid;
  //   grid-template-columns: repeat(3, 33.33%);
  grid-template-columns: repeat(auto-fill, 400px);
  //   grid-template-rows: repeat(3, 33.33%);
  row-gap: 10px;
  padding-left: 100px;
  .card-item {
    position: relative;
    span {
      position: absolute;
      color: rgb(35, 35, 31);
      font-weight: bold;
      left: 20px;
    }
  }
}
.btns {
  display: flex;
  justify-content: flex-end;
  button {
    margin: 0 5px;
    margin-top: 10px;
  }
}
</style>
